import React from 'react';
import {
  Button, Card, Col, Empty,
  Input, InputNumber, Layout, Modal,
  Row, Tree, TreeSelect,
} from 'antd';
import { Form } from '@ant-design/compatible';
import { IconButton, PageHeaderLayout, StandardTable } from '../../components';
import { connect } from 'dva';
import tools from '../../utils';
import {modalWidth, pageSize} from '../../../config';
import Authorized from '../../utils/Authorized';

const basicName = '班级';
const reqApi = 'classroom';
const { Sider, Content } = Layout;
const formItemLayout2 = {
  labelCol: { md: 6, xs: 8 },
  wrapperCol: { md: 18, xs: 16 },
};

class page extends React.Component {
  state = {
    currentNavi: '',
    loadingNavi: false,
    loading: false,
    visible: false,
    dialogLoading: false,
    dialogTitle: '',
    dialogAction: '',
    selectedRows: [],
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },
    editId: 0,
  };

  componentDidMount() {
    this.funcGetNaviData();
  }

  // 获取菜单数据
  funcGetNaviData = () => {
    this.setState({ loadingNavi: true });

    const { props } = this;
    props.dispatch({
      type: reqApi + '/listSpecial',
      payload: {
        currentPage: 1,
        pageSize: 1000,
      },
    }).then(() => {
      this.setState({ loadingNavi: false });
      this.funcGetListData();
    });
  };

  // 获取列表数据
  funcGetListData = () => {
    this.setState({
      loading: true,
      selectedRows: [], // 换页时清除表格行选中状态
    });

    const { state } = this;
    const { pagination } = state;
    const { current, pageSize } = pagination;
    const searchs = [];
    const { dispatch } = this.props;

    if (state.currentNavi) {
      searchs.push({
        name: "specialId",
        value: state.currentNavi,
        searchType: "EQ",
        dataType: "STR",
      });
    }

    dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: current,
        pageSize,
        searchs,
      },
    }).then(() => this.setState({ loading: false }));
  };

  // 导航菜单
  naviMenu = () => {
    const { props } = this;
    const { treeData } = props[reqApi];

    if (treeData.length) {
      return (
        <div style={{ maxHeight: 'calc(100vh - 120px)', overflow: 'auto' }}>
          <Tree
            defaultExpandAll
            treeData={treeData}
            onSelect={(selectedKeys) => {
              this.setState({
                currentNavi: selectedKeys.length ? selectedKeys[0] : "",
              }, this.funcGetListData);
            }}
          />
        </div>
      );
    } else return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const dialogAction = record ? "edit" : "create";
    this.setState({
      visible: true,
      dialogTitle: tools.funcDlgTitle(basicName, dialogAction),
      dialogAction,
    }, () => {
      const { props } = this;
      if (dialogAction === "edit") {
        const { name, remark, specialId, size } = record;
        const newRecord = {
          name,
          remark,
          specialId,
          size,
        };
        props.form.setFieldsValue(newRecord);
      } else {
        props.form.resetFields();
        const { state } = this;
        if (state.currentNavi) {
          props.form.setFieldsValue({ specialId: state.currentNavi });
        }
      }
    });
  };

  // 删除
  funcDelete = () => {
    const { state } = this;
    let names = [], ids = [];
    for (let i = 0; i < state.selectedRows.length; i += 1) {
      const item = state.selectedRows[i];
      const { id, name } = item;
      names.push(name);
      ids.push(id);
    }

    Modal.confirm({
      title: "删除?",
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{names + ''}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: "是",
      okType: "danger",
      cancelText: "否",
      onOk: () => this.funcDeleteExecute(ids + ''),
    });
  };

  // 执行删除
  funcDeleteExecute = (ids) => {
    this.setState({ loading: true });

    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/dele',
      payload: { ids },
    }).then(() => {
      const { props } = this;
      const { success } = props[reqApi];
      if (success) this.funcGetListData();
      else this.setState({ loading: false });
    });
  };

  // 保存
  funcSave = () => {
    const { state } = this;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      this.setState({ dialogLoading: true });

      const model = { ...values };
      if (state.dialogAction === "edit") {
        model.id = state.editId;
      }

      dispatch({
        type: reqApi + '/' + state.dialogAction,
        payload: { model },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ visible: false });
          this.funcGetListData();
        }
      });
    });
  };

  // 表格列
  columns = () => {
    const { props } = this;

    return [
      {
        title: "所属专业",
        dataIndex: "specialName",
        width: 200,
      },
      {
        title: basicName + '名称',
        dataIndex: "name",
        type: "text",
        render: (text, record) => (
          <Authorized authority={() => tools.funcCheckValid(props, 'edit')} noMatch={text}>
            <a
              title="编辑"
              onClick={() => {
                this.funcOpenForm(record);
                this.setState({ editId: record.id });
              }}
            >
              {text}
            </a>
          </Authorized>
        ),
      },
      {
        title: "容纳人数",
        dataIndex: "size",
        width: 100,
        render: text => text + ' 人',
      },
    ];
  };

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { data, total } = props[reqApi];

    return (
      <div>
        <Button.Group>
          <Authorized authority={() => tools.funcCheckValid(props, 'create')}>
            <IconButton
              text={'新增' + basicName}
              onClick={() => this.funcOpenForm()}
              style={{ marginBottom: 16 }}
            />
          </Authorized>
          <Authorized authority={() => tools.funcCheckValid(props, 'delete')}>
            <IconButton
              text={'删除' + basicName}
              type='danger'
              onClick={this.funcDelete}
              disabled={!state.selectedRows.length}
              style={{ marginBottom: 16 }}
            />
          </Authorized>
        </Button.Group>
        <StandardTable
          loading={state.loading}
          columns={this.columns()}
          data={{
            list: data,
            pagination: { ...state.pagination, total },
          }}
          selectedRows={state.selectedRows}
          onSelectRow={(selectedRows) => this.setState({ selectedRows })}
        />
      </div>
    );
  };

  render() {
    const { state, props } = this;
    const { getFieldDecorator } = props.form;

    return (
      <PageHeaderLayout title={props.route.name}>
        <Card bordered={false} bodyStyle={{ padding: 0 }}>
          <Layout>
            <Sider
              theme="light"
              style={{
                borderRight: "1px solid gainsboro",
              }}>
              {this.naviMenu()}
            </Sider>
            <Content
              style={{
                padding: "16px 8px 0 8px",
                backgroundColor: "white",
              }}>
              {this.contentTable()}
            </Content>
          </Layout>
        </Card>

        <Modal
          width={modalWidth}
          title={state.dialogTitle}
          visible={state.visible}
          onOk={this.funcSave}
          onCancel={() => this.setState({ visible: false })}
          bodyStyle={{ paddingBottom: 0 }}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ visible: false })}
            />,
            <IconButton
              key='save'
              text='保存'
              loading={state.dialogLoading}
              onClick={this.funcSave}
            />,
          ]}
        >
          <Form>
            <Row gutter={{ md: 24, sm: 8 }}>
              <Col md={12} sm={24}>
                <Form.Item label={basicName + '名称'} {...formItemLayout2}>
                  {getFieldDecorator("name", {
                    rules: [{ required: true, message: '请输入' + basicName + '名称' }],
                  })(<Input maxLength={20} autoFocus />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="所属专业" {...formItemLayout2}>
                  {getFieldDecorator("specialId", {
                    rules: [{ required: true, message: '请选择所属专业' }],
                  })(
                    <TreeSelect
                      treeDefaultExpandAll
                      dropdownStyle={{ maxHeight: 292 }}
                      treeData={props[reqApi].treeData}
                    />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="容纳人数" {...formItemLayout2}>
                  {getFieldDecorator("size", { initialValue: 56 })(
                    <InputNumber min={0} max={100} step={10} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="备注" {...formItemLayout2}>
                  {getFieldDecorator("remark")(
                    <Input.TextArea maxLength={255} rows={1} />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ classroom, menu }) => ({ classroom, menu }))(page2);
